// NLP 核心类型定义
type Intent = "load_imagery" | "fly_to" | "add_model" | "zoom" | "unknown";

type Entity = {
	location?: string;
	coordinates?: [number, number];
	model_name?: string;
	height?: number;
	zoom_level?: "in" | "out";
};

// 预训练关键词映射（可扩展）
const INTENT_KEYWORDS: Record<Intent, string[]> = {
	load_imagery: ["加载", "显示", "展示", "卫星", "影像"],
	fly_to: ["飞到", "前往", "定位到"],
	add_model: ["添加", "放置", "模型", "3D模型"],
	zoom: ["放大", "缩小", "拉近", "推远"],
	unknown: [],
};

// 核心 NLP 处理器
class CesiumNLP {
	// 意图识别
	static detectIntent(text: string): Intent {
		const lowerText = text.toLowerCase();

		for (const [intent, keywords] of Object.entries(INTENT_KEYWORDS)) {
			if (keywords.some((kw) => lowerText.includes(kw))) {
				return intent as Intent;
			}
		}
		return "unknown";
	}

	// 实体提取
	static extractEntities(text: string): Entity {
		const entities: Entity = {};

		// 提取坐标（支持多种格式）
		const coordRegex =
			/([北南]纬)?\s*(\d+\.?\d*)[°，]?\s*([东经西]经)?\s*(\d+\.?\d*)/g;
		const coordMatch = coordRegex.exec(text);
		if (coordMatch) {
			entities.coordinates = [
				parseFloat(coordMatch[2]),
				parseFloat(coordMatch[4]),
			];
		}

		// 提取高度/距离
		const heightRegex = /(\d+)(米|m|公里|km)/;
		const heightMatch = text.match(heightRegex);
		if (heightMatch) {
			entities.height = this.convertToMeters(
				parseFloat(heightMatch[1]),
				heightMatch[2]
			);
		}

		// 提取模型名称（简单匹配）
		const modelRegex = /(模型|添加|放置)\s*([\u4e00-\u9fa5a-zA-Z]+)/;
		const modelMatch = model.match(modelRegex);
		if (modelMatch) {
			entities.model_name = modelMatch[2];
		}

		// 使用地理位置服务解析地名
		const locationMatch = text.match(
			/[北南东西]京|上海|纽约|伦敦|[\u4e00-\u9fa5]{2,5}市?/
		);
		if (locationMatch) {
			entities.location = locationMatch[0];
		}

		// 提取缩放方向
		if (text.includes("放大") || text.includes("拉近")) {
			entities.zoom_level = "in";
		} else if (text.includes("缩小") || text.includes("推远")) {
			entities.zoom_level = "out";
		}

		return entities;
	}

	// 完整解析流程
	static parseCommand(text: string): { intent: Intent; entities: Entity } {
		return {
			intent: this.detectIntent(text),
			entities: this.extractEntities(text),
		};
	}

	private static convertToMeters(value: number, unit: string): number {
		const units: Record<string, number> = {
			米: 1,
			m: 1,
			公里: 1000,
			km: 1000,
		};
		return value * (units[unit] || 1);
	}
}

// 使用示例
const testCommands = [
	"加载纽约的卫星影像",
	"飞到北纬31.23°，东经121.47°，高度1000米",
	"在中心位置添加一个风力发电机模型",
	"放大两倍",
];

testCommands.forEach((command) => {
	const result = CesiumNLP.parseCommand(command);
	console.log(`命令: ${command}`);
	console.log(`解析结果:`, result);
	console.log("-------------------");
});

/**************** 输出示例 ****************
命令: 加载纽约的卫星影像
解析结果: {
  intent: "load_imagery",
  entities: { location: "纽约" }
}

命令: 飞到北纬31.23°，东经121.47°，高度1000米
解析结果: {
  intent: "fly_to",
  entities: { 
    coordinates: [31.23, 121.47],
    height: 1000
  }
}
*****************************************/
